<?php


namespace app\controller;


use app\model\Blogs;
use app\model\Permissions;
use app\model\Users;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use think\facade\Session;

class Login
{
    // 登录页面
    public function loginPage()
    {
        // 判断是否在登录状态
        if (Session::get('islogin'))
        {
            return View::fetch('user/info', ['nav' => 'info']);
        } else {
            return View::fetch('login/login');
        }
    }

    // 登录提交
    public function login(Request $request)
    {
        $username = $request::param('username');
        $password = $request::param('password');

        $vali_uname_res = Users::where('name', $username)
            ->whereOr('email', $username)
            ->find();

        // 判断用户是否存在
        if ($vali_uname_res == null) {
            return json(['code' => 400, 'msg' => '用户名或邮箱不存在']);
        } else {
            // 获取用户密码
            $vali_passwd_res = Users::where('name', $username)
                ->whereOr('email', $username)
                ->value('password');

            // 获取用户名称
            $name = Users::where('name', $username)
                ->whereOr('email', $username)
                ->value('name');

            // 判断密码是否正确
            if (md5($password) == $vali_passwd_res) {
                // 获取用户id
                $uid = Users::where('name', $name)
                    ->value('id');

                // 获取用户邮箱
                $email = Users::where('name', $username)
                    ->whereOr('email', $username)
                    ->value('email');

                // 获取用户头像
                $avatar = Users::where('name', $name)
                    ->value('avatar');

                $role_id = Users::where('name', $username)
                    ->value('role');

                // Seession 存储用户信息
                Session::set('name', $name);
                Session::set('uid', $uid);
                Session::set('email', $email);
                Session::set('islogin', 1);
                Session::set('avatar', $avatar);
                Session::set('role_id', $role_id);


                return json(['code' => 200, 'msg' => '登录成功']);
            } else {
                return json(['code' => 400, 'msg' => '密码错误']);
            }
        }
    }

    // 注册页面
    public function registerPage()
    {
        if (Session::get('islogin'))
        {
            return View::fetch('user/info', ['nav' => 'info']);
        } else {
            return View::fetch('login/register');
        }
    }

    // 注册提交
    public function register(Request $request)
    {
        $name = $request::param('name');
        $email = $request::param('email');
        $exampleInputPassword1 = $request::param('exampleInputPassword1');
        $exampleInputPassword2 = $request::param('exampleInputPassword2');
        $avatar = '/storage/avatar/default/davatar.png';

        // 注册信息
        $data = ['name' => $name,
        'email' => $email,
        'password' => $exampleInputPassword1,
        'password_confirm' => $exampleInputPassword2,
        'avatar' => $avatar,
        'created_at' => date('Y-m-d h:i:s', time())];

        // 验证注册信息
        try {
            validate(\app\validate\User::class)
                ->batch(true)
                ->check($data);
        } catch (ValidateException $e) {
            // 获取错误信息
            $errors_arr = $e->getError();
            $errors = '';
            // 将错误信息遍历拼接成一个字符串
            foreach ($errors_arr as $error)
            {
                $errors = $errors.$error.'<br>';
            }

            // 返回错误信息
            return json(['code' => 400, 'msg' => $errors]);
        }

        // 删除$data中的password_confirm键值
        unset($data['password_confirm']);

        // 为密码md5加密
        $data['password'] = md5($data['password']);

        // 插入数据库
        Users::insert($data);

        // 自动登录，添加session
        Session::set('name', $name);
        Session::set('uid', Users::where('name', $name)->value('id'));
        Session::set('email', $email);
        Session::set('islogin', 1);
        Session::set('avatar', $avatar);

        // 返回响应信息
        return json(['code' => 200, 'msg' => '注册成功！']);
    }

    // 登出
    public function logout()
    {
        // 清空Session
        Session::clear();

        // 重定向到主页
        return redirect('/');
    }
}